package com.bestv.bsr.standlone.service.impl.zt;

import cn.hutool.core.collection.CollUtil;
import com.bestv.bsr.core.annotations.OptionalComponent;
import com.bestv.bsr.core.constants.ServiceCodeEnum;
import com.bestv.bsr.core.context.RecommendContext;
import com.bestv.bsr.core.entities.vo.RecDataVo;
import com.bestv.bsr.core.exceptions.ServiceException;
import com.bestv.bsr.core.service.impl.zt.AbstractZTRecommendEngine;
import com.bestv.bsr.core.service.impl.zt.dto.ZTRequestParam;
import com.bestv.bsr.core.service.impl.zt.dto.ZTResponseDto;
import com.bestv.bsr.core.service.impl.zt.enums.EngineType;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author taojiacheng
 */
@Slf4j
@RequiredArgsConstructor
@OptionalComponent(value = "ztRecommendEngine", strategy = OptionalComponent.Strategy.STANDALONE)
public class LocalZTRecommendEngine extends AbstractZTRecommendEngine {

    @Override
    public RecDataVo recommend(RecommendContext recommendContext) {
        List<String> itemTypeList = recommendContext.getItemTypes();
        Set<String> leftTypes = new HashSet<>(itemTypeList);
        ZTResponseDto responseDto;
        ZTRequestParam ztRequestParam = buildZtRequestParams(recommendContext);
        // 默认使用itemBase推荐
        EngineType engineType = EngineType.ITEM_BASE;
        if (StringUtils.equals("1", recommendContext.getSceneType())) {
            // 直播推荐场景
            engineType = EngineType.CHANNEL_PREFER;
        }
        // 调用中台远程推荐服务
        responseDto = ztRemoteService.recommend(ztRequestParam, engineType.getCode());
        if (responseDto != null && !CollectionUtils.isEmpty(responseDto.getData())) {
            // 根据itemType 将数据平均分配
            responseDto = handlerZTResponse(leftTypes, responseDto);
        }
        return convertResponse(responseDto);
    }


    @Override
    public void validate(RecommendContext recommendContext) {
        if (StringUtils.isBlank(recommendContext.getUserId())) {
            log.error("userId is null");
            throw new ServiceException(ServiceCodeEnum.SCENE_ID_NOT_SUPPORTED);
        }
        Map<String, String> itemTypeMap = properties.getItemTypeMap();
        List<String> itemTypes = recommendContext.getItemTypes();
        List<String> intersection = itemTypes.stream().filter(itemTypeMap::containsKey).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(intersection)) {
            return;
        }
        log.error("itemTypes:{} notSupported:", CollUtil.join(itemTypes, ","));
        throw new ServiceException(ServiceCodeEnum.ITEM_TYPES_NOT_SUPPORTED);
    }

}
